package com.platform.common.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class BeanUtils {

    /**
     * 将 Object 对象转化成 map
     * @param obj
     * @return
     */
    public static Map toMap(Object obj){
        Map map = new HashMap();
        if(null != obj ){
            Class clazz = obj.getClass();
            do{
                Field[] fields = clazz.getDeclaredFields();
                for(Field field : fields ){
                    String name = field.getName();
                    if("serialVersionUID".equals(name)) continue;
                    try {
                        Method method = clazz.getMethod("get"+initCap(name), null);
                        map.put(name, method.invoke(obj, null));
                    } catch (Exception e) {
                        e.printStackTrace();
                        fields = null;
                    }
                }
                //获取父类属性
                clazz = clazz.getSuperclass();
            }while(clazz != Object.class);
        }
        return map;
    }

    /**s
     * @description 替换DTO属性名称首字母为大写 如：name-->Name
     * @param attr
     * @return 大写形式的属性名称
     */
    private static String initCap(String attr){
        return attr.substring(0, 1).toUpperCase()+attr.substring(1);
    }


}
